import { request, summary, body, tags, middlewares, path,prefix, security,description,responses }  from 'koa-swagger-decorator';
import Headers from '../middleware/Headers';  
const tag = tags(['用户相关']);
//解析token
const tools = require('../util/jwt')
import {successfn,abnormalfn,expfn} from "../util/status"
 
//引入数据表模型
const model = require('../database/model');
const User =  model.User
// 关联用户信息表
User.hasOne(model.UserInfo, {foreignKey: 'user_id', sourceKey: 'id'})

if(process.env.NODE_INIT==='true'){
    User.sync({
        force: true,//是否清空数据库表
    }).then(function() {
        console.log('ok');
    }); 
}

const userSchema = {
    mobileNo: { type: 'string', required: true ,example: '136021036201',description:"手机号"},
    password: { type: 'string', required: true , example: '123',description:"密码"}
  };

//数据库操作类
class userModule {
    static async userRegist(data) {
        return await User.create({
            password: data.password,
            mobileNo: data.mobileNo
        })
    }

    static async getUserInfo(mobileNo) {
        return await User.findOne({
            where: {
                mobileNo
            },
            attributes: { exclude: ['password'] },
            include: [ {
                model: model.UserInfo
              }]
        })
    }
}

//功能处理
@prefix('/user')
export default class userController {
    //注册用户
    @request('POST', '/register')
    @summary('注册用户')
    // @description('example of api')
    @tag
    @security([{ api_key: [] }]) 
    @body(userSchema)
    @responses({ 200: { description: 'success',
        "schema": {
            "type": "object",
            "items": {
                // $ref: "#/definitions/user"
            }
        }}})
    static async create(ctx) {
        const req = ctx.validatedBody;
       
        if (req.mobileNo && req.password) {
            try {
                const query = await userModule.getUserInfo(req.mobileNo);
                if (query) {
                    ctx.body = abnormalfn({ msg: "用户已存在" });
                } else {
                    const param = {
                        password: req.password,
                        mobileNo: req.mobileNo
                    }
                    const data = await userModule.userRegist(param);
                    const token = await tools.createToken(data);
                    const res =  await userModule.getUserInfo(req.mobileNo);
                    ctx.body =successfn({ 
                        msg: "用户注册成功",
                        data:{res,token}
                    })  
                 
                }

            } catch (error) {
                ctx.body = abnormalfn({  msg: "参数不齐全" })
            }
        }
    }
    @request('post', '/login')
    @summary('手机号，密码登录')
    @tag
   
    @body(userSchema)
    static async login(ctx) {
        console.log("登录")
        const req =  ctx.validatedBody;//ctx.request.body;
        if (!req.mobileNo || !req.password) {
            ctx.body = abnormalfn({ msg: "用户名或密码不能为空" });  
        } else {
            const data = await userModule.getUserInfo(req.mobileNo);
            if (data) {
                if (data.passWord === req.passWord) {
                    //生成token，验证登录有效期
                    const token = await tools.createToken(data);
                    delete data.passWord
                    ctx.body =successfn({ 
                        msg: "登陆成功",
                        data:{data,token}
                    })   
                } else {
                    return ctx.body = abnormalfn({ msg: "用户密码错误" }) 
                }
            } else {
                return ctx.body =  abnormalfn({ msg: "该用户尚未注册" }) 
            }
        };
    }
    //获取用户信息(除密码外)
    @request('post', '/getUserInfo')
    @summary('获取用户信息')
    @tag
    @middlewares(Headers())
    @body({ mobileNo: { type: 'string', required: true }})
    static async getUserInfo(ctx){
        const req = ctx.validatedBody;
        ctx.response.set("Cache-Control",'max-age=31536000;public');
        console.log(132443)
        if (!req.mobileNo) {
            ctx.body = abnormalfn({  msg: "参数错误" }) 
        } else {
            let data = await userModule.getUserInfo(req.mobileNo);
            // delete data.password
            if (req.mobileNo == data.mobileNo) {
                const info = {
                    createdAt: data.createdAt,
                    updatedAt: data.updatedAt,
                    mobileNo: data.mobileNo,
                    userId: data.userId
                };
                return ctx.body =successfn({ 
                    msg: "获取用户信息成功",
                    data: data
                  })
            }
        }
             
         
    }
   
}
 